import React, { forwardRef, useImperativeHandle } from 'react';
import useForm from './useForm';
import FieldContext from './FieldContext';

function Form({ children, onFinish, onFinishFailed, form }, ref) {
  const [formInstance] = useForm(form);
  formInstance.setCallback({ onFinish, onFinishFailed });

  useImperativeHandle(ref, () => {
    return formInstance;
  });

  return (
    <form
      onSubmit={(e) => {
        e.stopPropagation();
        e.preventDefault();
        formInstance.submit();
      }}
    >
      <FieldContext.Provider value={formInstance}>{children}</FieldContext.Provider>
    </form>
  );
}

export default forwardRef(Form);
